package info.wangyuan.agent.service.curd.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import info.wangyuan.agent.common.Constant.AgentConstant;
import info.wangyuan.agent.common.Enum.ModelType;
import info.wangyuan.agent.entity.po.AgentConfig;
import info.wangyuan.agent.exception.BusinessException;
import info.wangyuan.agent.mapper.AgentConfigMapper;
import info.wangyuan.agent.service.curd.CommonService;
import info.wangyuan.agent.service.event.AgentDeletedEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 智能体配置服务实现类
 *
 * @author Albert
 * @since 2025-07-14 02:35:12
 */
@Slf4j
@Service
public class AgentConfigService extends ServiceImpl<AgentConfigMapper, AgentConfig> {

    private final CommonService commonService;
    private final AgentConfigMapper agentConfigMapper;
    private final ApplicationEventPublisher publisher;

    public AgentConfigService(CommonService commonService, AgentConfigMapper agentConfigMapper, ApplicationEventPublisher publisher) {
        this.commonService = commonService;
        this.agentConfigMapper = agentConfigMapper;
        this.publisher = publisher;
    }

    /**
     * 智能体列表
     */
    public List<AgentConfig> list() {
        List<AgentConfig> agentConfigs = agentConfigMapper.selectList(null);
        if (CollUtil.isEmpty(agentConfigs)) {
            return agentConfigs;
        }

        Map<Integer, List<String>> agentKnowledgeMap = commonService.getKnowledgeBaseNamesForAgents(
                agentConfigs.stream()
                        .map(AgentConfig::getId)
                        .collect(Collectors.toSet())
        );

        for (AgentConfig agentConfig : agentConfigs) {
            agentConfig.setKnowledgeBaseNames(agentKnowledgeMap.getOrDefault(agentConfig.getId(), new ArrayList<>()));
        }

        return agentConfigs;
    }

    /**
     * 根据 id 获取 Agent 绑定的知识库名称
     */
    public List<String> getKnowledgeBaseNames() {
        Integer activeAgentId = getOne(
                Wrappers.lambdaQuery(AgentConfig.class)
                        .eq(AgentConfig::getEnabled, AgentConstant.ON)
        ).getId();
        if (activeAgentId == null) {
            return Collections.emptyList();
        }
        return commonService.getKnowledgeBaseNamesByAgentId(activeAgentId);
    }

    /**
     * 添加智能体
     */
    public void canAdd(AgentConfig agentConfig) {
        boolean exists = lambdaQuery()
                .eq(AgentConfig::getName, agentConfig.getName())
                .exists();
        if (exists) {
            throw new BusinessException("已存在同名 Agent");
        }

        commonService.checkModelIfNotExist(agentConfig.getChatModelId(), ModelType.LLM.getValue());
        commonService.checkPromptIfNotExist(agentConfig.getSystemPromptId());
        agentConfig.setEnabled(AgentConstant.OFF);
        agentConfigMapper.insert(agentConfig);
    }

    /**
     * 修改智能体
     */
    public void canUpdate(AgentConfig agentConfig) {
        Integer id = agentConfig.getId();
        commonService.checkAgentIfNotExist(id);
        AgentConfig dbAgent = getById(id);

        long count = count(
                Wrappers.lambdaQuery(AgentConfig.class)
                        .eq(AgentConfig::getEnabled, AgentConstant.ON)
        );

        // 不允许全部停用
        if (dbAgent.getEnabled().equals(AgentConstant.ON) && agentConfig.getEnabled().equals(AgentConstant.OFF) && count <= 1) {
            throw new BusinessException("修改失败，必须有一个 Agent 为使用状态");
        }

        // 激活当前 Agent，同时停用其他激活的 Agent
        if (dbAgent.getEnabled().equals(AgentConstant.OFF) && agentConfig.getEnabled().equals(AgentConstant.ON)) {
            // 先把所有激活的设为停用
            agentConfigMapper.update(
                    Wrappers.lambdaUpdate(AgentConfig.class)
                            .set(AgentConfig::getEnabled, AgentConstant.OFF)
                            .eq(AgentConfig::getEnabled, AgentConstant.ON)
            );
            commonService.activeModel(agentConfig.getChatModelId(), ModelType.LLM.getValue());
            commonService.checkPromptIfNotExist(agentConfig.getSystemPromptId());
            // 再激活当前 Agent
            agentConfig.setEnabled(AgentConstant.ON);
        }
        agentConfigMapper.updateById(agentConfig);
    }

    /**
     * 删除智能体
     */
    @Transactional
    public void canDelete(Integer id) {
        commonService.checkAgentIfNotExist(id);
        AgentConfig dbAgent = getById(id);
        if (dbAgent.getEnabled().equals(AgentConstant.ON)) {
            throw new BusinessException("当前 Agent 正在使用中，请先停止使用");
        }
        agentConfigMapper.deleteById(dbAgent);
        // 发布事件清除相关元数据
        publisher.publishEvent(new AgentDeletedEvent(id));
    }

}
